import _defineProperty from "@babel/runtime/helpers/esm/defineProperty";
import _objectSpread from "@babel/runtime/helpers/esm/objectSpread2";
import _toConsumableArray from "@babel/runtime/helpers/esm/toConsumableArray";
import _classCallCheck from "@babel/runtime/helpers/esm/classCallCheck";
import _createClass from "@babel/runtime/helpers/esm/createClass";
import _inherits from "@babel/runtime/helpers/esm/inherits";
import _createSuper from "@babel/runtime/helpers/esm/createSuper";
import _applyDecoratedDescriptor from "@babel/runtime/helpers/esm/applyDecoratedDescriptor";
import _filter from "lodash/filter";
import _isEmpty from "lodash/isEmpty";
import _map from "lodash/map";
import _join from "lodash/join";
import _forEach from "lodash/forEach";

var _dec, _dec2, _dec3, _dec4, _dec5, _dec6, _class, _class2, _class3;

/**
 * ButtonEdit.js * @date 2018-12-11
 */

/**
 * 要保证几种层级的命名都不能相同
 * param 表示有这个属性
 * param: 表示上级属性值有不同的分支
 *
 * action
 *  page:
 *    pageCode
 *    pageMeaning
 *    openType
 *      drawer:
 *        openPageTypeDrawer
 *      modal:
 *        openPageTypeModal
 *    params
 *    subEvents
 *    modalBtns
 *  action:
 *    actionEvent
 */
import React from 'react';
import { Form, Tabs, Row, Col, Select, Radio, Button, Tooltip, Input, Popconfirm } from 'antd';
import { Bind } from 'lodash-decorators';
import intl from 'utils/intl';
import { getEditTableData, getResponse, getCurrentOrganizationId } from 'utils/utils';
import Lov from 'components/Lov';
import EditTable from 'components/EditTable';
import { ACTION_CODE, // 按钮动作的方式
ACTION_PAGE_TYPE, // 打开页面的方式
PAGE_PARAM, // 页面参数类型
PAGE_TYPE_MODAL, // 弹出模态框的样式
paramSep, // 参数分隔
pageParamOptions, //  页面参数类型 选项
modalBtnSep, // 按钮分隔
subEventSep, // 订阅事件分隔
modalBtnPrefix, // 按钮前缀
subEventPrefix, // 订阅事件前缀
modalSubEvents, // 订阅事件
clickActionOptions, // 按钮动作的方式 选项
btnTypeOptions, // 按钮类型 选项
pageTypeModalOptions, // 弹出模态框的样式 选项
openPageOptions // 打开页面的方式 选项
} from 'components/DynamicComponent/config';
import DynamicTable from 'components/DynamicComponent/DynamicTable';
import DynamicForm from 'components/DynamicComponent/DynamicForm';
import DynamicModal from 'components/DynamicComponent/DynamicModal';
import DynamicToolbar from 'components/DynamicComponent/DynamicToolbar';
import { queryTplAndScriptsByPageCode } from "../../../../../services/uiPageService";
import DataType from "../../DataType";
import { attributeNameProp, attributeTypeProp, attributeValueProp } from "../../config";
import styles from "../index.less?modules";
var FormItem = Form.Item;
var col2Layout = {
  span: 12
}; // 分为两行, 有的需要跨行 用 formItemLayout1
// 不需要跨行的 用 formItemLayout2

var formItemLayout1 = {
  labelCol: {
    span: 3
  },
  wrapperCol: {
    span: 21
  }
};
var formItemLayout2 = {
  labelCol: {
    span: 6
  },
  wrapperCol: {
    span: 18
  }
};

function buildTplFuncOptGroup() {
  var tpl = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};

  if (tpl.templateCode) {
    var tplComponent;
    var tplName;

    switch (tpl.templateType) {
      case 'DynamicForm':
        tplComponent = DynamicForm;
        tplName = 'DynamicForm';
        break;

      case 'DynamicModal':
        tplComponent = DynamicModal;
        tplName = 'DynamicModal';
        break;

      case 'DynamicTable':
        tplComponent = DynamicTable;
        tplName = 'DynamicTable';
        break;

      case 'DynamicToolbar':
        tplComponent = DynamicToolbar;
        tplName = 'DynamicToolbar';
        break;

      default:
        break;
    }

    if (tplComponent) {
      if (tplComponent.exportFuncs && tplComponent.exportFuncs.length > 0) {
        return /*#__PURE__*/React.createElement(Select.OptGroup, {
          label: tpl.description,
          key: "".concat(tpl.templateCode, "-").concat(tplName)
        }, _map(tplComponent.exportFuncs, function (exportFuncStr) {
          return /*#__PURE__*/React.createElement(Select.Option, {
            key: "".concat(tpl.templateCode, "-").concat(tplName, "-").concat(exportFuncStr),
            value: "this.ref[".concat(tpl.templateCode, "].").concat(exportFuncStr)
          }, intl.get(tplComponent.exportFuncsInfo[exportFuncStr].descriptionIntlCode).d(tplComponent.exportFuncsInfo[exportFuncStr].descriptionIntlDefault));
        }));
      }
    }
  }

  return false;
}

function buildTplsFuncOptGroup(tpls) {
  var optGroups = [];

  _forEach(tpls, function (tpl) {
    var optGroup = buildTplFuncOptGroup(tpl);

    if (optGroup) {
      optGroups.push(optGroup);
    }
  });

  return optGroups;
}

function buildSelectOption(opt) {
  return /*#__PURE__*/React.createElement(Select.Option, {
    key: opt.value,
    value: opt.value,
    title: opt.meaning
  }, opt.meaning);
}

function buildRadioOption(opt) {
  return /*#__PURE__*/React.createElement(Radio, {
    key: opt.value,
    value: opt.value
  }, opt.meaning);
}

function buildSelect(options, parentProps) {
  return React.createElement(Select, parentProps, _map(options, buildSelectOption));
}

function buildRadioGroup(options, parentProps) {
  return React.createElement(Radio.Group, parentProps, _map(options, buildRadioOption));
}

var ButtonEdit = (_dec = Form.create({
  fieldNameProp: null
}), _dec2 = Bind(), _dec3 = Bind(), _dec4 = Bind(), _dec5 = Bind(), _dec6 = Bind(), _dec(_class = (_class2 = (_class3 = /*#__PURE__*/function (_React$Component) {
  _inherits(ButtonEdit, _React$Component);

  var _super = _createSuper(ButtonEdit);

  function ButtonEdit() {
    var _this;

    _classCallCheck(this, ButtonEdit);

    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }

    _this = _super.call.apply(_super, [this].concat(args));
    _this.state = {
      prevState: {},
      // 存储用来比较 更新的变量
      extraTabKey: 'param' // 为按钮执行动作 设置选项

    };
    _this.paramColumns = [{
      title: '序号',
      key: 'orderSeq',
      width: 80,
      render: function render(item, record, index) {
        return index + 1;
      }
    }, {
      title: '参数名称',
      dataIndex: 'paramName',
      width: 200,
      render: function render(item, record, index) {
        var _this$state$extraPara = _this.state.extraParamMap,
            extraParamMap = _this$state$extraPara === void 0 ? {} : _this$state$extraPara;
        var _record$$form = record.$form,
            getFieldDecorator = _record$$form.getFieldDecorator,
            getFieldError = _record$$form.getFieldError,
            getFieldValue = _record$$form.getFieldValue;
        var paramNameError = getFieldError('paramName');
        var hasError = !!paramNameError;
        var paramType = getFieldValue('paramType');
        var extraParam = extraParamMap[paramType] || {};
        var inputComponent;

        if (extraParam.getParamNameElement) {
          inputComponent = extraParam.getParamNameElement(item, record, index);
        } else {
          inputComponent = /*#__PURE__*/React.createElement(Input, {
            className: "".concat(hasError ? styles['border-error'] : '', " full-width"),
            inputChinese: false,
            trim: true
          });
        }

        return /*#__PURE__*/React.createElement(Tooltip, {
          title: _join(paramNameError),
          placement: "bottom"
        }, getFieldDecorator('paramName', {
          initialValue: item,
          rules: [{
            required: true,
            message: intl.get('cpaas.common.validation.notNull', {
              name: '参数名称'
            })
          }, {
            pattern: new RegExp("^[^".concat(paramSep, "]*$")),
            message: "\u53C2\u6570\u540D\u79F0\u4E0D\u80FD\u5305\u542B ".concat(paramSep)
          }]
        })(inputComponent));
      }
    }, {
      title: '参数类型',
      dataIndex: 'paramType',
      width: 120,
      render: function render(item, record) {
        var _record$$form2 = record.$form,
            getFieldDecorator = _record$$form2.getFieldDecorator,
            setFieldsValue = _record$$form2.setFieldsValue,
            getFieldError = _record$$form2.getFieldError,
            getFieldValue = _record$$form2.getFieldValue;
        var paramTypeError = getFieldError('paramType');
        var hasError = !!paramTypeError;
        var _this$state = _this.state,
            extraParams = _this$state.extraParams,
            extraParamMap = _this$state.extraParamMap;
        var paramType = getFieldValue('paramType');
        var extraParam = extraParamMap[paramType] || {};
        return /*#__PURE__*/React.createElement(Tooltip, {
          title: _join(paramTypeError),
          placement: "bottom"
        }, getFieldDecorator('paramType', {
          initialValue: item,
          rules: [{
            required: true,
            message: intl.get('cpaas.common.validation.notNull', {
              name: '参数类型'
            })
          }]
        })( /*#__PURE__*/React.createElement(Select, {
          className: "".concat(hasError ? styles['border-error'] : '', " full-width"),
          onChange: function
            /* paramType */
          onChange() {
            if (extraParam.getParamNameElement) {
              setFieldsValue({
                paramValue: undefined,
                paramName: undefined
              });
            } else {
              setFieldsValue({
                paramValue: undefined
              });
            } // if(extraParam.getParamValueElement) {
            //
            // }

          }
        }, _map([].concat(_toConsumableArray(pageParamOptions), _toConsumableArray(extraParams)), buildSelectOption))));
      }
    }, {
      title: '参数值',
      dataIndex: 'paramValue',
      width: 200,
      render: function render(item, record, index) {
        var _record$$form3 = record.$form,
            getFieldDecorator = _record$$form3.getFieldDecorator,
            getFieldValue = _record$$form3.getFieldValue,
            getFieldError = _record$$form3.getFieldError;
        var paramValueError = getFieldError('paramValue');
        var hasError = !!paramValueError;
        var paramType = getFieldValue('paramType');
        var extraParamMap = _this.state.extraParamMap;
        var extraParam = extraParamMap[paramType] || {};
        var inputComponent;

        if (extraParam.getParamValueElement) {
          inputComponent = extraParam.getParamValueElement(item, record, index);
        } else {
          inputComponent = /*#__PURE__*/React.createElement(Input, {
            className: "".concat(hasError ? styles['border-error'] : '', " full-width")
          });
        }

        if (inputComponent) {
          return /*#__PURE__*/React.createElement(Tooltip, {
            title: _join(paramValueError),
            placement: "bottom"
          }, getFieldDecorator('paramValue', {
            initialValue: item,
            rules: [{
              required: true,
              message: intl.get('cpaas.common.validation.notNull', {
                name: '参数值'
              })
            }, {
              pattern: new RegExp("^[^".concat(paramSep, "]*$")),
              message: "\u53C2\u6570\u503C\u4E0D\u80FD\u5305\u542B ".concat(paramSep)
            }]
          })(inputComponent));
        }

        return null;
      }
    }, {
      title: intl.get('cpaas.common.button.delete').d('删除'),
      key: 'delete',
      width: 80,
      render: function render(item, record) {
        return /*#__PURE__*/React.createElement(Form.Item, null, /*#__PURE__*/React.createElement(Popconfirm, {
          title: intl.get('cpaas.common.message.confirm.remove').d('确定删除选中数据？'),
          onConfirm: function onConfirm() {
            return _this.handleRemoveParam(record);
          }
        }, /*#__PURE__*/React.createElement("a", null, intl.get('cpaas.common.button.delete').d('删除'))));
      }
    }];
    _this.subEventColumns = [{
      title: '序号',
      key: 'orderSeq',
      width: 80,
      render: function render(item, record, index) {
        var getFieldDecorator = record.$form.getFieldDecorator; // 将序号放在数据中

        getFieldDecorator('orderSeq', {
          initialValue: index
        });
        return index + 1;
      }
    }, {
      title: '订阅事件',
      dataIndex: 'subEventListen',
      width: 200,
      render: function render(item, record) {
        var _record$$form4 = record.$form,
            getFieldDecorator = _record$$form4.getFieldDecorator,
            getFieldError = _record$$form4.getFieldError;
        var subEventListenError = getFieldError('subEventListen');
        var hasError = !!subEventListenError;
        return /*#__PURE__*/React.createElement(Tooltip, {
          title: _join(subEventListenError),
          placement: "bottom"
        }, getFieldDecorator('subEventListen', {
          initialValue: item,
          rules: [{
            required: true,
            message: intl.get('cpaas.common.validation.notNull', {
              name: '订阅事件'
            })
          }]
        })( /*#__PURE__*/React.createElement(Select, {
          className: "".concat(hasError ? styles['border-error'] : '', " full-width"),
          disabled: true
        }, _map(modalSubEvents, buildSelectOption))));
      }
    }, {
      title: '触发事件',
      dataIndex: 'subEventAction',
      width: 200,
      render: function render(item, record) {
        var _record$$form5 = record.$form,
            getFieldDecorator = _record$$form5.getFieldDecorator,
            getFieldError = _record$$form5.getFieldError;
        var subEventActionError = getFieldError('subEventAction');
        var hasError = !!subEventActionError;
        var extraActions = _this.props.extraActions;
        var actionOptions = _this.state.actionOptions;
        return /*#__PURE__*/React.createElement(Tooltip, {
          title: _join(subEventActionError),
          placement: "bottom"
        }, getFieldDecorator('subEventAction', {
          initialValue: item,
          rules: [{
            required: true,
            message: intl.get('cpaas.common.validation.notNull', {
              name: '触发事件'
            })
          }]
        })( /*#__PURE__*/React.createElement(Select, {
          className: "".concat(hasError ? styles['border-error'] : '', " full-width")
        }, actionOptions, extraActions)));
      }
    }];
    _this.modalBtnColumns = [{
      title: '序号',
      key: 'orderSeq',
      width: 80,
      render: function render(item, record, index) {
        var getFieldDecorator = record.$form.getFieldDecorator; // 将序号放在数据中

        getFieldDecorator('orderSeq', {
          initialValue: index
        });
        return index + 1;
      }
    }, {
      title: '按钮名称(按钮名称必须唯一)',
      dataIndex: 'btnName',
      width: 200,
      render: function render(item, record) {
        var _record$$form6 = record.$form,
            getFieldDecorator = _record$$form6.getFieldDecorator,
            getFieldError = _record$$form6.getFieldError;
        var btnNameError = getFieldError('btnName');
        var hasError = !!btnNameError;
        return /*#__PURE__*/React.createElement(Tooltip, {
          title: _join(btnNameError),
          placement: "bottom"
        }, getFieldDecorator('btnName', {
          initialValue: item,
          rules: [{
            required: true,
            message: intl.get('cpaas.common.validation.notNull', {
              name: '按钮编码'
            })
          }, {
            pattern: new RegExp("^[^".concat(modalBtnSep, "]*$")),
            message: "\u6309\u94AE\u7F16\u7801\u4E0D\u80FD\u5305\u542B ".concat(modalBtnSep)
          }]
        })( /*#__PURE__*/React.createElement(Input, {
          className: "".concat(hasError ? styles['border-error'] : '', " full-width"),
          trim: true
        })));
      }
    }, {
      title: '按钮类型',
      dataIndex: 'btnType',
      width: 120,
      render: function render(item, record) {
        var _record$$form7 = record.$form,
            getFieldDecorator = _record$$form7.getFieldDecorator,
            getFieldError = _record$$form7.getFieldError;
        var btnTypeError = getFieldError('btnType');
        var hasError = !!btnTypeError;
        return /*#__PURE__*/React.createElement(Tooltip, {
          title: _join(btnTypeError),
          placement: "bottom"
        }, getFieldDecorator('btnType', {
          initialValue: item,
          rules: []
        })( /*#__PURE__*/React.createElement(Select, {
          className: "".concat(hasError ? styles['border-error'] : '', " full-width")
        }, _map(btnTypeOptions, buildSelectOption))));
      }
    }, {
      title: '执行动作',
      dataIndex: 'btnAction',
      width: 200,
      render: function render(item, record) {
        var _record$$form8 = record.$form,
            getFieldDecorator = _record$$form8.getFieldDecorator,
            getFieldError = _record$$form8.getFieldError;
        var btnActionError = getFieldError('btnAction');
        var hasError = !!btnActionError; // pageEvents 页面的事件 extraEvents 额外的事件, 例如 表格组件的删除行

        var _this$state$pageActio = _this.state.pageActions,
            pageActions = _this$state$pageActio === void 0 ? [] : _this$state$pageActio;
        var _this$props$extraActi = _this.props.extraActions,
            extraActions = _this$props$extraActi === void 0 ? [] : _this$props$extraActi;
        return /*#__PURE__*/React.createElement(Tooltip, {
          title: _join(btnActionError),
          placement: "bottom"
        }, getFieldDecorator('btnAction', {
          initialValue: item
        })( /*#__PURE__*/React.createElement(Select, {
          className: "".concat(hasError ? styles['border-error'] : '', " full-width")
        }, pageActions, extraActions)));
      }
    }, {
      title: intl.get('cpaas.common.button.delete').d('删除'),
      key: 'delete',
      width: 80,
      render: function render(item, record) {
        return /*#__PURE__*/React.createElement(Form.Item, null, /*#__PURE__*/React.createElement(Popconfirm, {
          title: intl.get('cpaas.common.message.confirm.remove').d('确定删除选中数据？'),
          onConfirm: function onConfirm() {
            return _this.handleRemoveModalBtn(record);
          }
        }, /*#__PURE__*/React.createElement("a", null, intl.get('cpaas.common.button.delete').d('删除'))));
      }
    }];
    return _this;
  }

  _createClass(ButtonEdit, [{
    key: "render",
    value: function render() {
      return /*#__PURE__*/React.createElement(Form, null, this.renderLevel1());
    }
  }, {
    key: "componentDidMount",
    value: function componentDidMount() {
      // 加载 modal 按钮 执行动作
      var _this$props = this.props,
          _this$props$propsValu = _this$props.propsValue,
          propsValue = _this$props$propsValu === void 0 ? {} : _this$props$propsValu,
          onRef = _this$props.onRef;

      if (propsValue.action === ACTION_CODE.page) {
        if (propsValue.pageCode && (propsValue.openType === ACTION_PAGE_TYPE.modal || propsValue.openType === ACTION_PAGE_TYPE.drawer)) {
          this.queryAndSetPageActions(propsValue.pageCode);
        }
      }

      if (onRef) {
        onRef(this);
      }
    }
  }, {
    key: "queryAndSetPageActions",
    value: function queryAndSetPageActions(pageCode) {
      var _this2 = this;

      var _this$props$organizat = this.props.organizationId,
          organizationId = _this$props$organizat === void 0 ? getCurrentOrganizationId() : _this$props$organizat; // 查询页面的 方法&tpl

      queryTplAndScriptsByPageCode(organizationId, pageCode).then(function (res) {
        var page = getResponse(res);

        if (page) {
          var pageActions = [];
          var pageScriptActions = [];

          if (page.scripts) {
            for (var i = 0; i < page.scripts.length; i += 1) {
              pageScriptActions.push( /*#__PURE__*/React.createElement(Select.Option, {
                value: page.scripts[i].name,
                key: page.scripts[i].name
              }, page.scripts[i].description));
            }
          }

          pageActions.push( /*#__PURE__*/React.createElement(Select.OptGroup, {
            label: page.description,
            key: "page-".concat(pageCode, "-script")
          }, pageScriptActions));

          if (page.tpls) {
            for (var _i = 0; _i < page.tpls.length; _i += 1) {
              var componentActionOptions = [];

              switch (page.tpls[_i].templateType) {
                case 'DynamicForm':
                  componentActionOptions.push( /*#__PURE__*/React.createElement(Select.Option, {
                    value: "this.ref[".concat(page.tpls[_i].templateCode, "].reset"),
                    key: "component-form-".concat(page.tpls[_i].templateCode, "-reset")
                  }, "\u91CD\u7F6E"));
                  componentActionOptions.push( /*#__PURE__*/React.createElement(Select.Option, {
                    value: "this.ref[".concat(page.tpls[_i].templateCode, "].submit"),
                    key: "component-form-".concat(page.tpls[_i].templateCode, "-submit")
                  }, "\u63D0\u4EA4"));
                  break;

                case 'DynamicTable':
                  componentActionOptions.push( /*#__PURE__*/React.createElement(Select.Option, {
                    value: "this.ref[".concat(page.tpls[_i].templateCode, "].reload"),
                    key: "component-table-".concat(page.tpls[_i].templateCode, "-reload")
                  }, "\u91CD\u65B0\u52A0\u8F7D"));
                  componentActionOptions.push( /*#__PURE__*/React.createElement(Select.Option, {
                    value: "this.ref[".concat(page.tpls[_i].templateCode, "].query"),
                    key: "component-table-".concat(page.tpls[_i].templateCode, "-query")
                  }, "\u67E5\u8BE2"));
                  break;
                // Toolbar 和 Modal 还没有自己的方法

                case 'DynamicToolbar':
                  break;

                case 'DynamicModal':
                  break;

                default:
                  break;
              }

              pageActions.push( /*#__PURE__*/React.createElement(Select.OptGroup, {
                label: page.tpls[_i].description,
                key: "component-".concat(page.tpls[_i].templateCode)
              }, componentActionOptions));
            }
          }

          _this2.setState({
            pageActions: pageActions
          });
        }
      });
    }
    /**
     * 打开页面 action, 页面改变后 需要重新查询 选择的页面拥有的方法
     * todo 需不需要清空 modal 按钮的事件
     * @param {String} pageCode
     */

  }, {
    key: "handlePageChange",
    value: function handlePageChange(pageCode) {
      var form = this.props.form;
      var prevPageCode = form.getFieldValue('pageCode');

      if (prevPageCode !== pageCode) {
        this.queryAndSetPageActions(pageCode);
      }
    }
    /**
     * 按钮事件 一层层嵌套 上级影响下级
     */

  }, {
    key: "renderLevel1",
    value: function renderLevel1() {
      var form = this.props.form;
      var _this$state$propsValu = this.state.propsValue,
          propsValue = _this$state$propsValu === void 0 ? {} : _this$state$propsValu; // 根据 action 去渲染 level2

      var initialAction = propsValue.action || ACTION_CODE.page; // action 是必输 且 是一个选项 不存在没有值;

      var action = form.getFieldValue('action') || initialAction;
      return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(Row, null, /*#__PURE__*/React.createElement(Col, col2Layout, /*#__PURE__*/React.createElement(FormItem, Object.assign({}, formItemLayout2, {
        key: "action",
        label: "\u52A8\u4F5C"
      }), form.getFieldDecorator('action', {
        initialValue: initialAction,
        rules: [{
          required: true,
          message: intl.get('cpaas.common.validation.notNull', {
            name: '动作'
          })
        }]
      })(buildRadioGroup(clickActionOptions))))), this.renderLevel2(action));
    }
  }, {
    key: "renderLevel2",
    value: function renderLevel2(action) {
      switch (action) {
        case ACTION_CODE.page:
          return this.renderLevel2Page();

        case ACTION_CODE.action:
          return this.renderLevel2Action();

        default:
          break;
      }

      return null;
    }
  }, {
    key: "renderLevel2Page",
    value: function renderLevel2Page() {
      var form = this.props.form;
      var _this$state2 = this.state,
          _this$state2$propsVal = _this$state2.propsValue,
          propsValue = _this$state2$propsVal === void 0 ? {} : _this$state2$propsVal,
          extraTabKey = _this$state2.extraTabKey;
      var initialOpenType = propsValue.openType || ACTION_PAGE_TYPE.drawer;
      var openType = form.getFieldValue('openType') || initialOpenType;
      var openTypeCascade;

      switch (openType) {
        case ACTION_PAGE_TYPE.drawer:
          openTypeCascade = /*#__PURE__*/React.createElement(Col, col2Layout, /*#__PURE__*/React.createElement(FormItem, Object.assign({}, formItemLayout2, {
            key: "openPageTypeDrawer",
            label: "\u6ED1\u51FA\u5C3A\u5BF8"
          }), form.getFieldDecorator('openPageTypeDrawer', {
            initialValue: propsValue.openPageTypeDrawer || 520
          })( /*#__PURE__*/React.createElement(Radio.Group, null, /*#__PURE__*/React.createElement(Radio, {
            value: 520
          }, "520"), /*#__PURE__*/React.createElement(Radio, {
            value: 1000
          }, "1000")))));
          break;

        case ACTION_PAGE_TYPE.modal:
          openTypeCascade = /*#__PURE__*/React.createElement(Col, col2Layout, /*#__PURE__*/React.createElement(FormItem, Object.assign({}, formItemLayout2, {
            key: "openPageTypeModal",
            label: intl.get('cpfm.ui.model.field.linkButton.openPageTypeModal').d('弹出尺寸')
          }), form.getFieldDecorator('openPageTypeModal', {
            initialValue: propsValue.openPageTypeModal || PAGE_TYPE_MODAL.w1
          })(buildSelect(pageTypeModalOptions))));
          break;

        case ACTION_PAGE_TYPE.open:
          break;

        default:
          break;
      } // 给 pageMeaning 设置值


      form.getFieldDecorator('pageMeaning', {
        initialValue: propsValue.pageMeaning
      });
      return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(Row, null, /*#__PURE__*/React.createElement(Col, null, /*#__PURE__*/React.createElement(FormItem, Object.assign({}, formItemLayout1, {
        key: "pageCode",
        label: "\u9009\u62E9\u9875\u9762"
      }), form.getFieldDecorator('pageCode', {
        initialValue: propsValue.pageCode,
        rules: [{
          required: true,
          message: intl.get('cpaas.common.validation.notNull', {
            name: '页面'
          })
        }]
      })( /*#__PURE__*/React.createElement(Lov, {
        code: "CPFM.UI_PAGE",
        className: "full-width",
        textField: "pageMeaning",
        onChange: this.handlePageChange
      }))))), /*#__PURE__*/React.createElement(Row, null, /*#__PURE__*/React.createElement(Col, col2Layout, /*#__PURE__*/React.createElement(FormItem, Object.assign({}, formItemLayout2, {
        key: "openType",
        label: intl.get('cpfm.ui.model.field.linkButton.openType').d('打开方式')
      }), form.getFieldDecorator('openType', {
        initialValue: initialOpenType
      })(buildSelect(openPageOptions)))), openTypeCascade), /*#__PURE__*/React.createElement(Row, null, /*#__PURE__*/React.createElement(Col, null, /*#__PURE__*/React.createElement(Form.Item, {
        key: "extra"
      }, /*#__PURE__*/React.createElement(Tabs, {
        animated: false,
        activeKey: extraTabKey,
        tabBarExtraContent: /*#__PURE__*/React.createElement(React.Fragment, null, extraTabKey === 'param' && /*#__PURE__*/React.createElement("div", {
          style: {
            marginBottom: 10,
            textAlign: 'right'
          }
        }, /*#__PURE__*/React.createElement(Button, {
          icon: "plus",
          onClick: this.handleParamsAdd
        }))),
        onChange: this.handleExtraTabChange
      }, /*#__PURE__*/React.createElement(Tabs.TabPane, {
        forceRender: true,
        key: "param",
        tab: "\u4F20\u9012\u53C2\u6570"
      }, /*#__PURE__*/React.createElement(EditTable, {
        rowKey: this.getRowKey,
        columns: this.paramColumns,
        dataSource: propsValue.params,
        pagination: false,
        bordered: true
      })), openType === ACTION_PAGE_TYPE.modal || openType === ACTION_PAGE_TYPE.drawer ? [/*#__PURE__*/React.createElement(Tabs.TabPane, {
        forceRender: true,
        key: "subEvent",
        tab: "\u8BA2\u9605\u4E8B\u4EF6"
      }, /*#__PURE__*/React.createElement(EditTable, {
        rowKey: this.getRowKey,
        columns: this.subEventColumns,
        dataSource: propsValue.subEvents,
        pagination: false,
        bordered: true
      })), /*#__PURE__*/React.createElement(Tabs.TabPane, {
        forceRender: true,
        key: "modalBtn",
        tab: "\u6309\u94AE"
      }, /*#__PURE__*/React.createElement(EditTable, {
        rowKey: this.getRowKey,
        columns: this.modalBtnColumns,
        dataSource: propsValue.modalBtns,
        pagination: false,
        bordered: true
      }))] : null)))));
    }
  }, {
    key: "renderLevel2Action",
    value: function renderLevel2Action() {
      var _this$props2 = this.props,
          form = _this$props2.form,
          extraActions = _this$props2.extraActions;
      var _this$state3 = this.state,
          _this$state3$propsVal = _this$state3.propsValue,
          propsValue = _this$state3$propsVal === void 0 ? {} : _this$state3$propsVal,
          actionOptions = _this$state3.actionOptions;
      return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(Row, null, /*#__PURE__*/React.createElement(Col, col2Layout, /*#__PURE__*/React.createElement(FormItem, Object.assign({}, formItemLayout2, {
        key: "actionEvent",
        label: "\u6267\u884C\u52A8\u4F5C"
      }), form.getFieldDecorator('actionEvent', {
        initialValue: propsValue.actionEvent
      })( /*#__PURE__*/React.createElement(Select, null, actionOptions, extraActions))))));
    } // openType 页面参数表格相关

  }, {
    key: "getRowKey",
    value: function getRowKey(record, index) {
      return index;
    }
  }, {
    key: "handleParamsAdd",
    value: function handleParamsAdd() {
      var _this$state$propsValu2 = this.state.propsValue,
          propsValue = _this$state$propsValu2 === void 0 ? {} : _this$state$propsValu2;
      var _propsValue$params = propsValue.params,
          params = _propsValue$params === void 0 ? [] : _propsValue$params;
      this.setState({
        propsValue: _objectSpread(_objectSpread({}, propsValue), {}, {
          params: [].concat(_toConsumableArray(params), [{
            paramType: PAGE_PARAM.fixParam,
            _status: 'create'
          }])
        })
      });
    }
  }, {
    key: "handleRemoveParam",
    value: // Table 按钮事件
    function handleRemoveParam(record) {
      var _this$state$propsValu3 = this.state.propsValue,
          propsValue = _this$state$propsValu3 === void 0 ? {} : _this$state$propsValu3;
      this.setState({
        propsValue: _objectSpread(_objectSpread({}, propsValue), {}, {
          params: _filter(propsValue.params, function (r) {
            return r !== record;
          })
        })
      });
    }
  }, {
    key: "handleRemoveModalBtn",
    value: function handleRemoveModalBtn(record) {
      var _this$state$propsValu4 = this.state.propsValue,
          propsValue = _this$state$propsValu4 === void 0 ? {} : _this$state$propsValu4;
      this.setState({
        propsValue: _objectSpread(_objectSpread({}, propsValue), {}, {
          modalBtns: _filter(propsValue.modalBtns, function (r) {
            return r !== record;
          })
        })
      });
    }
    /**
     *
     * @returns Promise<object>
     */

  }, {
    key: "getValidateData",
    value: function getValidateData() {
      return this.getValidateLevel1Data();
    }
    /**
     * @return Promise<object>
     */

  }, {
    key: "getValidateLevel1Data",
    value: function getValidateLevel1Data() {
      var _this3 = this;

      var form = this.props.form;
      return new Promise(function (resolve, reject) {
        form.validateFields(function (err, fieldsValue) {
          if (err) {
            reject(err);
            return;
          }

          var action = fieldsValue.action;

          var validateData = _objectSpread({}, fieldsValue);

          var attrConfig = [];
          attrConfig.push({
            attributeName: 'action',
            attributeType: DataType.String,
            value: action
          });

          _this3.getValidateLevel2Data(action, validateData, attrConfig).then(function () {
            resolve({
              validateData: validateData,
              attrConfig: attrConfig
            });
          }, reject);
        });
      });
    }
    /**
     * 会改变 validateData
     * 将 level2 的数据放进去
     * @param {String} action
     * @param {object} validateData
     * @param {Array<{attributeName: String, attributeValue: any, dataType: String}>} attrConfig
     */

  }, {
    key: "getValidateLevel2Data",
    value: function getValidateLevel2Data(action, validateData, attrConfig) {
      switch (action) {
        case ACTION_CODE.page:
          return this.getValidateLevel2PageData(validateData, attrConfig);

        case ACTION_CODE.action:
          return this.getValidateLevel2ActionData(validateData, attrConfig);

        default:
          break;
      }

      return Promise.reject(new Error('不是已知的Action'));
    }
  }, {
    key: "getValidateLevel2PageData",
    value: function getValidateLevel2PageData(validateData, attrConfig) {
      var _attrConfig$push, _attrConfig$push2, _attrConfig$push3;

      var _this$state$propsValu5 = this.state.propsValue,
          propsValue = _this$state$propsValu5 === void 0 ? {} : _this$state$propsValu5;
      var editParams = propsValue.params; // 获取参数

      if (editParams && editParams.length) {
        // 有参数
        var validateParams = getEditTableData(editParams);

        if (!validateParams.length) {
          return Promise.reject(new Error('参数校验失败'));
        }

        var paramsStream = [];

        for (var i = 0; i < validateParams.length; i += 1) {
          paramsStream.push(validateParams[i].paramName);
          paramsStream.push(validateParams[i].paramType);
          paramsStream.push(validateParams[i].paramValue);
        } // eslint-disable-next-line no-param-reassign


        validateData.params = paramsStream.join(paramSep);
      } // 获取订阅事件


      var editSubEvents = propsValue.subEvents;

      if (editSubEvents && editSubEvents.length) {
        // 有参数
        var validateSubEvents = getEditTableData(editSubEvents);

        if (!validateSubEvents.length) {
          return Promise.reject(new Error('按钮校验失败'));
        }

        var subEventsConfig = [];
        var subEvents = [];

        for (var _i2 = 0; _i2 < validateSubEvents.length; _i2 += 1) {
          // modalBtn 是一个数组存储的数据
          subEvents.push({
            attributeType: DataType.String,
            value: "".concat(validateSubEvents[_i2].subEventListen).concat(subEventSep).concat(validateSubEvents[_i2].subEventAction)
          });
          subEventsConfig.push({
            attributeName: "".concat(subEventPrefix, "[").concat(_i2, "]"),
            attributeType: DataType.String,
            value: "".concat(validateSubEvents[_i2].subEventListen).concat(subEventSep).concat(validateSubEvents[_i2].subEventAction)
          });
        } // eslint-disable-next-line no-param-reassign


        validateData.subEvents = subEvents;
        attrConfig.push({
          attributeName: 'subEvents',
          value: subEventsConfig
        });
      } // 获取Modal按钮 和 事件


      var editModalBtns = propsValue.modalBtns;

      if (editModalBtns && editModalBtns.length) {
        // 有参数
        var validateModalBtns = getEditTableData(editModalBtns);

        if (!validateModalBtns.length) {
          return Promise.reject(new Error('按钮校验失败'));
        }

        var modalBtnsConfig = [];
        var modalBtns = [];

        for (var _i3 = 0; _i3 < validateModalBtns.length; _i3 += 1) {
          // modalBtn 是一个数组存储的数据
          modalBtns.push({
            attributeType: DataType.String,
            value: "".concat(validateModalBtns[_i3].btnName).concat(modalBtnSep).concat(validateModalBtns[_i3].btnType).concat(modalBtnSep).concat(validateModalBtns[_i3].btnAction)
          });
          modalBtnsConfig.push({
            attributeName: "".concat(modalBtnPrefix, "[").concat(_i3, "]"),
            attributeType: DataType.String,
            value: "".concat(validateModalBtns[_i3].btnName).concat(modalBtnSep).concat(validateModalBtns[_i3].btnType).concat(modalBtnSep).concat(validateModalBtns[_i3].btnAction)
          });
        } // eslint-disable-next-line no-param-reassign


        validateData.modalBtns = modalBtns;
        attrConfig.push({
          attributeName: 'modalBtns',
          value: modalBtnsConfig
        });
      }

      attrConfig.push({
        attributeName: 'openType',
        attributeType: DataType.String,
        value: validateData.openType
      });
      attrConfig.push((_attrConfig$push = {}, _defineProperty(_attrConfig$push, attributeNameProp, 'pageCode'), _defineProperty(_attrConfig$push, attributeValueProp, validateData.pageCode), _defineProperty(_attrConfig$push, attributeTypeProp, DataType.String), _attrConfig$push));
      attrConfig.push((_attrConfig$push2 = {}, _defineProperty(_attrConfig$push2, attributeNameProp, 'pageMeaning'), _defineProperty(_attrConfig$push2, attributeTypeProp, DataType.String), _defineProperty(_attrConfig$push2, attributeValueProp, validateData.pageMeaning), _attrConfig$push2));
      attrConfig.push((_attrConfig$push3 = {}, _defineProperty(_attrConfig$push3, attributeNameProp, 'params'), _defineProperty(_attrConfig$push3, attributeValueProp, validateData.params), _defineProperty(_attrConfig$push3, attributeTypeProp, DataType.String), _attrConfig$push3)); // 滑出

      if (validateData.openType === ACTION_PAGE_TYPE.drawer) {
        var _attrConfig$push4;

        attrConfig.push((_attrConfig$push4 = {}, _defineProperty(_attrConfig$push4, attributeNameProp, 'openPageTypeDrawer'), _defineProperty(_attrConfig$push4, attributeValueProp, validateData.openPageTypeDrawer), _defineProperty(_attrConfig$push4, attributeTypeProp, DataType.Number), _attrConfig$push4));
      } // 弹出


      if (validateData.openType === ACTION_PAGE_TYPE.modal) {
        var _attrConfig$push5;

        attrConfig.push((_attrConfig$push5 = {}, _defineProperty(_attrConfig$push5, attributeNameProp, 'openPageTypeModal'), _defineProperty(_attrConfig$push5, attributeValueProp, validateData.openPageTypeModal), _defineProperty(_attrConfig$push5, attributeTypeProp, DataType.String), _attrConfig$push5));
      }

      return Promise.resolve();
    }
  }, {
    key: "getValidateLevel2ActionData",
    value: function getValidateLevel2ActionData(validateData, attrConfig) {
      // warn 删除pageMeaning 的属性
      // eslint-disable-next-line no-param-reassign
      delete validateData.pageMeaning;

      if (validateData.actionEvent) {
        attrConfig.push({
          attributeName: 'actionEvent',
          attributeType: DataType.String,
          value: validateData.actionEvent
        });
      }

      return Promise.resolve();
    } // extraTab

  }, {
    key: "handleExtraTabChange",
    value: function handleExtraTabChange(tabKey) {
      this.setState({
        extraTabKey: tabKey
      });
    }
  }], [{
    key: "getDerivedStateFromProps",
    value:
    /**
     * 根据传进的属性 来生成 对应 打开页面 的参数
     */
    function getDerivedStateFromProps(nextProps, prevState) {
      var propsValue = nextProps.propsValue,
          extraParams = nextProps.extraParams,
          scripts = nextProps.scripts,
          components = nextProps.components;
      var _prevState$prevState = prevState.prevState,
          prevPropsValue = _prevState$prevState.propsValue,
          prevExtraParams = _prevState$prevState.extraParams,
          prevScripts = _prevState$prevState.scripts,
          prevComponents = _prevState$prevState.components;
      var nextState = {};
      var nextPrevState = {
        propsValue: prevPropsValue,
        extraParams: prevExtraParams
      }; // 设置 编辑属性值

      if (propsValue && prevPropsValue !== propsValue) {
        var nextPropsValue = _objectSpread({}, propsValue); // 处理打开页面情况, 默认是打开页面


        if (!propsValue.action || propsValue.action === ACTION_CODE.page) {
          // 处理参数
          var params = [];
          var paramStream = (propsValue.params || '').split(paramSep);

          for (var i = 1; i <= paramStream.length; i++) {
            if (i % 3 === 0) {
              params.push({
                paramName: paramStream[i - 3],
                paramType: paramStream[i - 2],
                paramValue: paramStream[i - 1],
                _status: 'update'
              });
            }
          }

          nextPropsValue.params = params; // 处理订阅事件
          // 处理 Modal 按钮

          var modalBtns = [];

          if (propsValue.modalBtns) {
            for (var _i4 = 0; _i4 < propsValue.modalBtns.length; _i4++) {
              var modalBtnStream = (propsValue.modalBtns[_i4].value || '').split(modalBtnSep);
              modalBtns.push({
                btnName: modalBtnStream[0],
                btnType: modalBtnStream[1],
                btnAction: modalBtnStream[2],
                _status: 'update'
              });
            }
          } else {
            modalBtns.push({
              btnName: '确定',
              btnType: 'primary',
              btnAction: undefined,
              _status: 'create'
            });
            modalBtns.push({
              btnName: '取消',
              btnType: '',
              btnAction: undefined,
              _status: 'create'
            });
          }

          nextPropsValue.modalBtns = modalBtns; // 处理 订阅事件

          var subEvents = [];

          if (propsValue.subEvents) {
            for (var _i5 = 0; _i5 < propsValue.subEvents.length; _i5++) {
              var subEventStream = (propsValue.subEvents[_i5].value || '').split(modalBtnSep);
              subEvents.push({
                subEventListen: subEventStream[0],
                subEventAction: subEventStream[1],
                _status: 'update'
              });
            }
          } else {
            modalSubEvents.forEach(function (modalSubEvent) {
              subEvents.push({
                subEventListen: modalSubEvent.value,
                subEventAction: undefined,
                _status: 'create'
              });
            });
          }

          nextPropsValue.subEvents = subEvents;
        } else if (propsValue.action === ACTION_CODE.action) {// 执行动作不需要额外处理
        }

        nextState.propsValue = nextPropsValue;
        nextPrevState.propsValue = propsValue;
      } // 为打开页面的 参数选项 设置额外的参数选项


      if (extraParams && prevExtraParams !== extraParams) {
        var nextExtraParamMap = {}; // 将 额外参数 数组转成 对象

        _forEach(extraParams, function (p) {
          nextExtraParamMap[p.value] = p;
        });

        nextState.extraParamMap = nextExtraParamMap;
        nextState.extraParams = extraParams;
        nextPrevState.extraParams = extraParams;
      } // 为执行动作 设置选项


      if (scripts && scripts !== prevScripts || components && components !== prevComponents) {
        nextPrevState.scripts = scripts;
        nextPrevState.components = components;
        var travelScripts = scripts || [];
        var travelComponents = components || [];
        var actionOptions = [];
        var scriptPageActionOptions = [];

        for (var _i6 = 0; _i6 < travelScripts.length; _i6++) {
          scriptPageActionOptions.push( /*#__PURE__*/React.createElement(Select.Option, {
            value: "this.".concat(scripts[_i6].name),
            key: "page-script-".concat(scripts[_i6].name)
          }, scripts[_i6].description));
        } // 给执行动作的选项加入 页面方法


        actionOptions.push( /*#__PURE__*/React.createElement(Select.OptGroup, {
          label: "\u9875\u9762\u65B9\u6CD5",
          key: "page-$-script"
        }, scriptPageActionOptions));
        actionOptions = actionOptions.concat(buildTplsFuncOptGroup(travelComponents));
        nextState.actionOptions = actionOptions;
      } // 为执行动作 设置额外的组件方法, 由父组件提供, 不需要处理 直接是好的 OptGroup


      if (_isEmpty(nextState)) {
        return null;
      }

      nextState.prevState = nextPrevState;
      return nextState;
    }
  }]);

  return ButtonEdit;
}(React.Component), _class3.defaultProps = {
  extraActions: [],
  extraParams: [],
  propsValue: {}
}, _class3), (_applyDecoratedDescriptor(_class2.prototype, "queryAndSetPageActions", [_dec2], Object.getOwnPropertyDescriptor(_class2.prototype, "queryAndSetPageActions"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "handlePageChange", [_dec3], Object.getOwnPropertyDescriptor(_class2.prototype, "handlePageChange"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "handleParamsAdd", [_dec4], Object.getOwnPropertyDescriptor(_class2.prototype, "handleParamsAdd"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "getValidateData", [_dec5], Object.getOwnPropertyDescriptor(_class2.prototype, "getValidateData"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "handleExtraTabChange", [_dec6], Object.getOwnPropertyDescriptor(_class2.prototype, "handleExtraTabChange"), _class2.prototype)), _class2)) || _class);
export { ButtonEdit as default };